import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, Form, Input, Row, Spin, Button, message, TreeSelect } from 'antd';
import React, { Ref, useEffect, useMemo, useRef } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { getLoadMapList, getTenantID, onCloseModalCommon } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { UploadFormCommon } from '@/components/UploadForm';
import { addTempInfoService, editTempService, getTempByIdService, signTempService } from '../services';
import { loopTreeContractType } from '../mconfig';

export const UpdateViewModal: React.FC<TempContractManageAPI.IUpdateViewModal> = ({ onClose, checkRowsInfo, reloadManage, curRes }) => {
  /** 弹框Ref */
  const updateTempModalRef: Ref<IOneModalRef> = useRef(null);

  /** form表单实例 */
  const [updateForm] = Form.useForm();

  /** 获取数据字典loadMdicMap */
  const { loadMapInfo, mapLoading }: Record<string, any> = getLoadMapList([
    // `${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_TYPE}`, //合同范本类型
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`, //范本类别
  ]);

  /** 关闭弹框 */
  const onCloseModal = () => {
    onCloseModalCommon(updateTempModalRef);
  };

  /** 详情接口回调 */
  const detailCallback = (res: any) => {
    if (res && res?.msgFlag) {
      // message.success(res?.msg);
      updateForm?.setFieldsValue({
        ...res?.obj,
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情接口 */
  const { getTempByIdInfo, getTempByIdLoading, getTempByIdRun } = getTempByIdService(detailCallback);

  /** 签发回调 */
  const signCallabck = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
      onCloseModalCommon(updateTempModalRef);
    } else {
      message.error(res?.msg);
    }
  };

  /** 签发接口 */
  const { signTempLoading, signTempRun } = signTempService(signCallabck);

  /** 添加编辑弹框 */
  const updateCallback = (res: any, isPublish?: boolean) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);

      if (isPublish) {
        //签发
        const signPayload: Record<string, any> = {
          ...res?.obj,
          state: `${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_STATE}1002`,
          id: res?.obj?.id,
          versionNum: res?.obj?.versionNum,
        };
        signTempRun(signPayload);
      } else {
        reloadManage();
        onCloseModalCommon(updateTempModalRef);
      }
    } else {
      message.error(res?.msg);
    }
  };

  /** 添加接口口 */
  const { addTempInfoLoading, addTempInfoRun } = addTempInfoService(updateCallback);

  /** 编辑弹框 */
  const { editTempLoading, editTempRun } = editTempService(updateCallback);

  /**
   * 保存按钮
   * @param clickType  true 保存   false 发布
   */
  const onSave = (clickType: boolean) => {
    updateForm?.validateFields()?.then((values: any) => {
      const payload: Record<string, any> = {
        ...values,
        templateType: `${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_TYPE}1000`,
      };

      if (clickType) {
        //添加编辑
        if (checkRowsInfo?.id) {
          const editPayload: Record<string, any> = {
            ...payload,
            id: getTempByIdInfo?.id,
            state: getTempByIdInfo?.state,
            versionNum: getTempByIdInfo?.versionNum,
          };
          editTempRun(editPayload);
        } else {
          const addPayload: Record<string, any> = {
            ...payload,
            state: `${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_STATE}1000`,
          };
          addTempInfoRun(addPayload);
        }
      } else {
        if (checkRowsInfo?.id) {
          //签发
          const signPayload: Record<string, any> = {
            ...getTempByIdInfo,
            ...payload,
            state: `${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_STATE}1002`,
            id: getTempByIdInfo?.id,
            versionNum: getTempByIdInfo?.versionNum,
          };
          signTempRun(signPayload);
        } else {
          const addPayload: Record<string, any> = {
            ...payload,
            state: `${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_STATE}1000`,
            isPublish: true,
          };
          addTempInfoRun(addPayload);
        }
      }
    });
  };

  /** 初始化 */
  useEffect(() => {
    if (checkRowsInfo && checkRowsInfo?.id) {
      getTempByIdRun({
        id: checkRowsInfo?.id,
      });
    }
  }, [checkRowsInfo]);

  /** 处理合同类型树数据 */
  const contractTypeMemo = useMemo(() => {
    if (loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`]?.length > 0) {
      return loopTreeContractType(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`]);
    } else {
      return [];
    }
  }, [loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`]]);

  /** 弹框底部按钮 */
  const footerModal = useMemo(() => {
    return (
      <>
        <Button
          key="back"
          onClick={onCloseModal}
          // icon={<CloseCircleOutlined />}
        >
          关闭
        </Button>
        <Button
          key="submit"
          type="primary"
          loading={addTempInfoLoading || editTempLoading || getTempByIdLoading}
          // icon={<SaveOutlined />}
          onClick={() => {
            onSave(true);
          }}
        >
          暂存
        </Button>
        {curRes['/contractTemplateController/sign'] && !getTempByIdInfo?.id && (
          <Button
            key="issue"
            type="primary"
            loading={addTempInfoLoading || editTempLoading || getTempByIdLoading}
            // icon={<CheckCircleOutlined />}
            onClick={() => {
              onSave(false);
            }}
          >
            发布
          </Button>
        )}
        {/* {true && (
          <Button
            key="apply"
            type="primary"
            loading={addTempInfoLoading || editTempLoading || getTempByIdLoading}
            icon={<SendOutlined />}
          >
            提交
          </Button>
        )} */}
      </>
    );
  }, [curRes, signTempLoading, addTempInfoLoading, editTempLoading, getTempByIdLoading]);
  return (
    <OneModal
      open={true}
      ref={updateTempModalRef}
      width={document.body.clientWidth * 0.35}
      title={checkRowsInfo?.id ? '编辑范本' : '添加范本'}
      onCancel={onClose}
      bodyStyle={{
        padding: '5px 10px',
      }}
      centered
      footer={footerModal}
      confirmLoading={addTempInfoLoading || editTempLoading || getTempByIdLoading || signTempLoading}
    >
      <Spin spinning={addTempInfoLoading || editTempLoading || getTempByIdLoading || signTempLoading}>
        <div className={pageStyles['fromView-styles']}>
          <Form form={updateForm}>
            <Row>
              <Col span={24}>
                <Form.Item
                  label="范本名称"
                  name="fullName"
                  rules={[
                    {
                      required: true,
                      message: '请输入范本名称',
                    },
                  ]}
                >
                  <Input placeholder="请输入范本名称" allowClear />
                </Form.Item>
              </Col>
              {/* <Col span={24}>
                <Form.Item
                  label="范本类型"
                  name="templateType"
                  rules={[
                    {
                      required: true,
                      message: '请选择范本类型',
                    },
                  ]}
                >
                  <Select placeholder="请选择范本类型" allowClear loading={mapLoading}>
                    {loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_TYPE}`]?.map((item: any) => {
                      return (
                        <Select.Option key={item?.id} value={item?.id}>
                          {item?.name}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
              </Col> */}
              <Col span={24}>
                <Form.Item
                  label="合同类型"
                  name="businessType"
                  rules={[
                    {
                      required: true,
                      message: '请选择合同类型',
                    },
                  ]}
                >
                  <TreeSelect
                    placeholder="支持模糊搜索"
                    showSearch={true}
                    treeNodeFilterProp={'name'}
                    treeData={contractTypeMemo}
                    loading={mapLoading}
                    fieldNames={{ label: 'name', value: 'value', children: 'children' }}
                  />
                </Form.Item>
              </Col>
              <UploadFormCommon
                form={updateForm}
                fileFormName={'templateURL'}
                spanCol={24}
                inRowProportion={24}
                name={'attachFile'}
                url={'/contractTemplateController/uploadFile'}
                downloadUrl={'/contractTemplateController/downloadFile'}
                label="范本正文"
                required={true}
                accept={'.doc|.docx'}
                fileFormDelName={'templateURLDel'}
                delFunc={() => {}}
                maxFile={1}
                defaultFiles={getTempByIdInfo?.id ? getTempByIdInfo?.templateURL : null}
                isEdit={false}
                fieldBusiPath={'contract/template'}
              >
                上传文件
              </UploadFormCommon>
              <Col span={24}>
                <Form.Item
                  label="范本描述"
                  name="templateInfo"
                  rules={[
                    {
                      required: true,
                      message: '请输入范本描述',
                    },
                  ]}
                >
                  <Input.TextArea placeholder={`请输入范本描述`} showCount maxLength={800} autoSize={{ minRows: 4, maxRows: 8 }} />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
      </Spin>
    </OneModal>
  );
};
